﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using ChuanYe.Models.Model;
using ChuanYe.Commom;
using ChuanYe.Models;
using ChuanYe.DAL;
using System.Data;
namespace SJPlatForm.Web
{
    public class ChatHub : Hub
    {
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Type"></param>
        public void send(string ID, string Type)
        {
            try
            {
                List<MessageModel> Message = new List<MessageModel>();
             
                switch (Type)
                {
                    case "0":
                        Message = IndexDAL.GetMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID));
                        break;
                    case "1":
                        Message.Add(IndexDAL.GetMailMessage2(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)));
                        break;
                    case "2":
                        Message.Add(IndexDAL.GetDocumentMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)));
                        break;
                    case "3":
                        Message.Add(IndexDAL.GetScheduleMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)));
                        break;
                    case "4":
                        var automatics = IndexDAL.GetAutomatic(Convert.ToInt32(ID), 4, 0);
                        Message.Add(new MessageModel()
                        {
                            Automatics = automatics,
                            Count = automatics.Count,
                            Message = string.Empty,
                            Type = 4,
                        });
                        break;
                }
                
                int UserID = Convert.ToInt32(ID);
                List<string> List = UsersOnLionList.Where(m => m.UserID == UserID).Select(m=>m.ConnectionId).ToList();
                Clients.Clients(List).SendMessage(Message);
            }
            catch (Exception ex)
            {
                Log.Error("ChatHub", ex.ToString());
            }
        }


        /// <summary>
        /// 2018/09/20
        /// </summary>
        /// <param name="ID"></param>
        public void newSend(string ID)
        {
            try
            {
                List<dynamic> message = new List<dynamic>();

                message.Add(new {Type="0",Name="邮箱", Data= IndexDAL.GetMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)) });

                message.Add(new { Type = "1", Name = "未读邮件", Data = IndexDAL.GetMailMessage2(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)) });

                message.Add(new { Type = "2", Name = "公文提醒", Data = IndexDAL.GetDocumentMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)) });

                message.Add(new { Type = "3", Name = "日志提醒", Data = IndexDAL.GetScheduleMessage(Convert.ToInt32(ID), Convert.ToInt32(GetLoginInfo(ID).DepID)) });

                message.Add(new { Type = "4", Name = "日程提醒", Data = IndexDAL.GetAutomatic(Convert.ToInt32(ID),4)});

                int UserID = Convert.ToInt32(ID);
                List<string> List = UsersOnLionList.Where(m => m.UserID == UserID).Select(m => m.ConnectionId).ToList();
                Clients.Clients(List).SendMessage(message);
            }
            catch (Exception ex)
            {
                Log.Error("ChatHub newSend ", ex.ToString());
            }

        }


        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="Type"></param>
        public void sendCall(string Type)
        {
            Clients.All.SendMessageOnLion(Type);
        }
        /// <summary>
        /// 用户上线函数
        /// </summary>
        /// <param name="ID"></param>
        public void sendIn(string ID)
        {
            try
            {
                //Log.Error("1:", "入口");
                //添加在线客户端
                List<UsersOnLion> List = UsersOnLionList.Where(m => m.ConnectionId == Context.ConnectionId).ToList();
                if (List.Count() <= 0)
                {
                    UsersOnLion User = new UsersOnLion();
                    User.ConnectionId = Context.ConnectionId;
                    User.UserID = Convert.ToInt32(ID);
                    User.UserName = GetLoginInfo(ID).UserName;
                    UsersOnLionList.Add(User);

                    //添加在线值守
                    foreach (ManagerOnLion manager in ManagerOnLionList)
                    {
                        if (manager.UserID == User.UserID)
                        {
                            manager.OnLionCount = 1;
                        }
                    }
                }

                //网站浏览量
                int total = IndexDAL.GetBrowsingTotal();

                int userCount=UsersOnLionList.GroupBy(g => g.UserID).Select(s => s.Key).ToList().Count();

                ManagerOnLionList = ManagerOnLionList.OrderByDescending(o => o.OnLionCount).ThenBy(t => t.Sort).ToList();
               
                //更新在线值守
                Clients.All.loginUser(ManagerOnLionList, userCount, total);



            }
            catch (Exception ex)
            {
                Log.Error("sendIn ChatHub", ex.ToString());
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) 
        {
            try
            {
                if (stopCalled)
                {
                    //客户端退出登录
                    string ConnectionId = Context.ConnectionId;
                    UsersOnLion User = UsersOnLionList.FirstOrDefault(m => m.ConnectionId == ConnectionId);
                    UsersOnLionList.Remove(User);
                    //在线值守退出登录
                    foreach (ManagerOnLion manager in ManagerOnLionList)
                    {
                        if (manager !=null  && manager.UserID == User.UserID)
                        {
                            manager.OnLionCount = manager.OnLionCount - 1;
                        }
                    }
                    //网站浏览量
                    int total = IndexDAL.GetBrowsingTotal();


                    int userCount = UsersOnLionList.GroupBy(g => g.UserID).Select(s => s.Key).ToList().Count();
                    //更新在线值守
                    Clients.All.loginUser(ManagerOnLionList, userCount, total);
                }
                return base.OnDisconnected(stopCalled);
            }
            catch (Exception ex)
            {
                Log.Error(" OnDisconnected ChatHub", ex.ToString());
                return base.OnDisconnected(stopCalled);
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="ID"></param>
        public void sendOut(string ID)
        {
            try
            {
                //客户端退出登录
                string ConnectionId = Context.ConnectionId;
                UsersOnLion User = UsersOnLionList.FirstOrDefault(m => m.ConnectionId == ConnectionId);
                UsersOnLionList.Remove(User);
                //在线值守退出登录
                foreach (ManagerOnLion manager in ManagerOnLionList)
                {
                    if (manager.UserID == User.UserID)
                    {
                        manager.OnLionCount = 0;
                    }
                }
                //网站浏览量
                int total = IndexDAL.GetBrowsingTotal();

                int userCount = UsersOnLionList.GroupBy(g => g.UserID).Select(s => s.Key).ToList().Count();
               
                ManagerOnLionList = ManagerOnLionList.OrderByDescending(o => o.OnLionCount).ThenBy(t => t.Sort).ToList();
                //更新在线值守
                Clients.All.loginUser(ManagerOnLionList, userCount, total);
                //Clients.Client(Context.ConnectionId).serverOrderedDisconnect();
            }
            catch (Exception ex)
            {
                Log.Error("ChatHub", ex.ToString());
            }
        }

        /// <summary>
        /// 获取登录用户
        /// </summary>
        /// <returns></returns>
        public static List<UsersOnLion> GetUserOnLion()
        {
            return UsersOnLionList;
        }

        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        /// <param name="UID"></param>
        /// <returns></returns>
        public static LoginUserModel GetLoginInfo(string UID)
        {
            try
            {
                //return (LoginUserModel)System.Web.HttpContext.Current.Cache[UID];
                UsersInfosDAL s_DAL = new UsersInfosDAL();
                return s_DAL.LoginUserInfos(int.Parse(UID));
            }
            catch (Exception ex)
            {
                Log.Error("ChatHub", ex.ToString());
                return new LoginUserModel();
            }
        }

        /// <summary>
        /// 改变登录状态
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="IsLogin"></param>
        public static void LoginInfoUpdate(string UID, bool IsLogin)
        {
            try
            {
            }
            catch (Exception ex)
            {
                Log.Error("ChatHub", ex.ToString());
            }
        }

        /// <summary>
        /// 在线值守人员列表
        /// </summary>
        public static List<ManagerOnLion> ManagerOnLionList = IndexDAL.GetManager2();
        /// <summary>
        /// 在线用户列表
        /// </summary>
        public static List<UsersOnLion> UsersOnLionList = new List<UsersOnLion>();

    }
}